import React, { useState } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import style from './index.module.scss'
import { useDispatch } from 'react-redux'
import { getToken } from '@/store/actions/login'
import { useHistory } from 'react-router'
export default function Login () {
  const history = useHistory()
  const dispatch = useDispatch()
  const [loading, setloading] = useState(false)
  const onFinish = async (value) => {
    setloading(true)
    try {
      // 获取token 登录
      await dispatch(getToken(value))
      message.success('登录成功', () => {
        // 跳转页面
        history.replace('/home')
      })
    } catch (err) {
      message.error(err.response.data.message)
    } finally {
      setloading(false)
    }
  }
  return (
    <div className={style.login}>
      <Card className="login-container">
        <img src={logo} className="login-logo" alt="" />
        <Form
          validateTrigger={['onBlur', 'onChange']}
          size="large"
          onFinish={onFinish}
          initialValues={{
            agree: true,
            mobile: '13811111111',
            code: '246810'
          }}>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '手机号必填' },
              {
                pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '手机号不合法',
                validateTrigger: 'onBlur'
              }
            ]}>
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              {
                min: 6,
                max: 10,
                message: '密码6-10位',
                validateTrigger: 'onBlur'
              },
              { required: true, message: '密码必填' }
            ]}>
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            rules={[
              {
                validator (rule, value, callback) {
                  return value
                    ? Promise.resolve()
                    : Promise.reject(new Error('必填'))
                }
              }
            ]}>
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
